import axios from 'axios'
import qs from 'qs' 
import { ElMessage } from 'element-plus'

const service = axios.create({
  baseURL: import.meta.env.VITE_HOST,
  timeout: 15000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})

service.interceptors.request.use(
  config => {
    if (config.method?.toLowerCase() === 'get') {
      config.paramsSerializer = params => {
        return qs.stringify(params, { arrayFormat: 'repeat' })
      }
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    }

    if (config.data instanceof FormData) {
      config.headers['Content-Type'] = 'multipart/form-data'
    }

    const token = sessionStorage.getItem('accessToken')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    return config
  },
  error => Promise.reject(error)
)

service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== 200) {
      ElMessage.error(res.message || '请求失败，请稍后重试')
      return Promise.reject({
        code: res.code || -1,
        message: res.message || '未知错误',
        data: res.data
      })
    }
    
    return {
      code: 200,
      data: res.data,
      message: res.message || '请求成功'
    }
  },
  error => {
    ElMessage.error(errorInfo.message||'请求失败，请稍后重试')
    return Promise.reject(errorInfo)
  }
)


const http = {
  get(url, params, config = {}) {
    return service({
      method: 'get',
      url,
      params, 
      ...config
    })
  },

  post(url, data, config = {}) {
    return service({
      method: 'post',
      url,
      data, 
      ...config
    })
  },

  put(url, data, config = {}) {
    return service({
      method: 'put',
      url,
      data,
      ...config
    })
  },

  delete(url, params, config = {}) {
    return service({
      method: 'delete',
      url,
      params,
      ...config
    })
  }
}

export default http